<template>
  <div class="app-container">
    <!-- 巡查项目 -->
    <!-- 查询和其他操作 -->
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="设备编号">
        <el-input
          v-model="listQuery.fequipmentno"
          clearable
          class="filter-item"
          style="width: 200px"
          placeholder="请输入设备编号"
        />
      </el-form-item>
      <el-form-item label="设备名称">
        <el-input
          v-model="listQuery.fequipmentname"
          clearable
          class="filter-item"
          style="width: 200px"
          placeholder="请输入设备名称"
        />
      </el-form-item>
      <el-form-item label="设备分类">
        <el-select v-model="listQuery.fclassstno" filterable clearable class="filter-item" placeholder="请选择设备分类">
          <el-option
            v-for="item in getListfclassstno"
            :key="item.value"
            :label="item.label"
            :value="item.value"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <!-- v-permission="['inspection:equipmentInfo:read']" -->
        <el-button
          :style="{background:buttonColor.lookup,color:buttonColor.color}"
          round
          size="medium"
          class="filter-item"
          @click="handleFilter"
        >查找</el-button
        >
        <!-- v-permission="['inspection:equipmentInfo:create']" -->
        <el-button
          :style="{background:buttonColor.add,color:buttonColor.color}"
          round
          size="medium"
          class="filter-item"
          @click="handleCreate"
        >添加</el-button
        >
      </el-form-item>
    </el-form>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      :header-cell-style="tableColor"
      stripe
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
    >

      <el-table-column :width="buttonColor.operationTwo" align="center" label="操作" class-name="small-padding">
        <template slot-scope="scope">
          <div class="operationButton">
            <div :style="{color:buttonColor.edit,cursor:'pointer'}" @click="handleUpdate(scope.row)">
              <img src="../../../public/images/edit.png" >
              编辑
            </div>
            <div :style="{color:buttonColor.delete,cursor:'pointer'}" @click="handleDelete(scope.row)">
              <img src="../../../public/images/del.png" >
              删除
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column
        :index="indexMethod"
        align="center"
        label="序"
        type="index"
      />
      <el-table-column align="center" label="设备编号" prop="fequipmentno" />
      <el-table-column align="center" label="设备名称" prop="fequipmentname" />
      <el-table-column :formatter="formatfclassstno" align="center" label="设备分类" prop="fclassstno" />
      <el-table-column align="center" label="计量单位" prop="funit" />
      <el-table-column align="center" label="品牌" prop="fbrand" />
      <el-table-column align="center" label="型号" prop="fspec" />

    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 添加或修改对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible"
      :before-close="handleClose"
      width="auto"
    >
      <template slot="title">
        <div :style="titleColor">{{ textMap[dialogStatus] }}</div>
      </template>
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="dataForm"
        status-icon
        label-position="left"
        label-width="auto"
      >

        <el-row>
          <el-col :span="8">
            <el-form-item
              label="设备编号"
              prop="fequipmentno"
            >
              <div style="display:flex;justify-content:flex-end;align-items:center">
                <el-input v-model="dataForm.fequipmentno" style="display: inline-block" />
                <i style="display: inline-block;color:#409EFF;margin-left:3px" class="el-icon-search" @click="searchDialog"/>
              </div>
            </el-form-item
            >
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="设备名称"
              prop="fequipmentname"
            >
            <el-input :disabled="true" v-model="dataForm.fequipmentname" /> </el-form-item
            >
          </el-col>
          <el-col :span="8">
            <el-form-item
              label="设备分类"
              prop="fclassstno"
            >
              <el-select v-model="dataForm.fclassstno" disabled filterable clearable class="filter-item" placeholder="请选择设备分类">
                <el-option
                  v-for="item in getListfclassstno"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
            </el-select> </el-form-item
            >
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="品牌" prop="fbrand">
            <el-input :disabled="true" v-model="dataForm.fbrand" /> </el-form-item
            >
          </el-col>
          <el-col :span="8">
            <el-form-item label="计量单位" prop="funit">
            <el-input :disabled="true" v-model="dataForm.funit" /> </el-form-item
            >
          </el-col>
          <el-col :span="8">
            <el-form-item label="型号" prop="fspec">
            <el-input :disabled="true" v-model="dataForm.fspec" /> </el-form-item
            >
          </el-col>
        </el-row>

      </el-form>

      <el-tabs type="border-card">
        <el-tab-pane label="巡查列表">
          <div class="app-container">
            <!-- 子表查询和其他操作 -->
            <div class="filter-container">
              <el-button
                :style="{background:buttonColor.add,color:buttonColor.color}"
                round
                size="medium"
                class="filter-item"
                icon="el-icon-edit"
                @click="handleUpdate1"
              >添加</el-button
              >
            </div>

            <!-- 子表查询结果 -->
            <el-table
              v-loading="listLoading"
              :data="dataForm.details2"
              :header-cell-style="tableColor"
              stripe
              element-loading-text="正在查询中。。。"
              border
              fit
              highlight-current-row
              height="30vh"
            >
              <el-table-column
                align="center"
                label="行号"
                prop="fline"
              />
              <el-table-column
                align="center"
                label="巡查项目编号"
                prop="fcheckitemno"
              />
              <el-table-column
                align="center"
                label="巡查项目名称"
                prop="fcheckitemname"
              />
              <el-table-column
                :formatter="formatfchecktypeno"
                align="center"
                label="巡查类型"
                prop="fchecktypeno"
              />
              <el-table-column align="center" label="是否启用" prop="fcheckflag">
                <template slot-scope="scope">
                  <el-tag>{{ scope.row.fcheckflag | siteTypeFilter }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column align="center" label="备注" prop="fmemo" />
              <el-table-column
                align="center"
                label="操作"
                class-name="small-padding"
              >
                <template slot-scope="scope">
                  <el-button
                    :style="{background:buttonColor.delete,color:buttonColor.color}"
                    round
                    size="small"
                    class="button-margin"
                    @click="handleDelete1(scope.row)"
                  >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div>
      </el-tab-pane></el-tabs
      >

      <div slot="footer" class="dialog-footer">
        <el-button :style="{background:buttonColor.cancel,color:buttonColor.colorone}" @click="cancel()">取消</el-button>
        <el-button
          v-if="dialogStatus == 'create'"
          :style="{background:buttonColor.confirm,color:buttonColor.color}"
          @click="createData"
        >确定</el-button
        >
        <el-button v-else :style="{background:buttonColor.confirm,color:buttonColor.color}" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

    <!-- 子表添加或修改对话框 -->
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="dialogFormVisible1"
      width="auto"
    >
      <template slot="title">
        <div :style="titleColor">{{ textMap[dialogStatus] }}</div>
      </template>
      <el-form
        ref="dataForm1"
        :rules="rules1"
        :model="dataForm1"
        status-icon
        label-position="left"
        label-width="auto"
        style="width: 400px; margin: 0 30px"
      >
        <el-form-item label="行号" prop="fline">
          <el-input v-model="dataForm1.fline" disabled/>
        </el-form-item>
        <el-form-item label="项目编号" prop="fcheckitemno">
          <el-input v-model="dataForm1.fcheckitemno" />
        </el-form-item>
        <el-form-item label="项目名称" prop="fcheckitemname">
          <el-input v-model="dataForm1.fcheckitemname" />
        </el-form-item>
        <el-form-item label="巡查类型" prop="fchecktypeno">
          <el-select v-model="dataForm1.fchecktypeno" style="width:100%" filterable clearable class="filter-item" placeholder="请选择巡查类型">
            <el-option
              v-for="item in getListfchecktypeno"
              :key="item.value"
              :label="item.label"
              :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="是否启用" prop="fcheckflag">
          <el-select
            v-model="dataForm1.fcheckflag"
            clearable
            filterable
            class="filter-item"
            placeholder="是否启用"
            style="width:100%"
          >
            <el-option
              v-for="item in siteTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="fmemo">
          <el-input v-model="dataForm1.fmemo" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :style="{background:buttonColor.cancel,color:buttonColor.colorone}" @click="dialogFormVisible1 = false">取消</el-button>
        <el-button :style="{background:buttonColor.confirm,color:buttonColor.color}" @click="addData">确定</el-button>
      </div>
    </el-dialog>
    <!-- 设备搜索弹出框 -->
    <el-dialog
      :close-on-click-modal="false"
      :visible.sync="searchVisible"
      top="5vh"
      title="搜索"
    >
      <el-form :inline="true" class="demo-form-inline">
        <el-form-item label="设备编号">
          <el-input
            v-model="listQuerySearch.fequipmentno"
            clearable
            class="filter-item"
            style="width: 150px"
            placeholder="请输入设备编号"
          />
        </el-form-item>
        <el-form-item label="设备名称">
          <el-input
            v-model="listQuerySearch.fequipmentname"
            clearable
            class="filter-item"
            style="width: 150px"
            placeholder="请输入设备名称"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            :style="{background:buttonColor.lookup,color:buttonColor.color}"
            round
            size="medium"
            class="filter-item"
            icon="el-icon-search"
            @click="searchFilter"
          >查找</el-button
          >
        </el-form-item>
      </el-form>

      <!-- 查询结果 -->
      <el-table
        v-loading="listLoadingSearch"
        :data="searchList"
        :header-cell-style="tableColor"
        stripe
        element-loading-text="正在查询中。。。"
        border
        fit
        highlight-current-row
        height="300"
      >
        <el-table-column align="center" label="设备编号" prop="fequipmentno" />
        <el-table-column align="center" label="设备名称" prop="fequipmentname" />
        <el-table-column align="center" label="规格" prop="fspec" />
        <el-table-column
          align="center"
          label="选择"
          class-name="small-padding"
        >
          <template slot-scope="scope">
            <el-button
              :style="{background:buttonColor.confirm,color:buttonColor.color}"
              round
              size="small"
              class="button-margin"
              @click="searchData(scope.row)"
            >确定</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="totalSearch > 0"
        :total="totalSearch"
        :page.sync="listQuerySearch.page"
        :limit.sync="listQuerySearch.limit"
        style="padding:14px 10px !important"
        @pagination="getSearchList"
      />
    </el-dialog>
  </div>
</template>

<style>
.button-margin {
  margin: 2px 0px;
}
.el-button + .el-button {
  margin-left: 1px;
}
</style>

<script>
import { listinfo, createinfo, updateinfo, deleteinfo } from '@/api/info'
import { getListArea } from '@/api/area'
import Pagination from '@/components/Pagination'
import moment from 'moment'
import { tableColor, titleColor, buttonColor } from '@/filters/index'

const siteTypeMap = {
  0: '否',
  1: '是'
}

export default {
  name: 'STsEquipmentInfo',
  components: { Pagination },
  filters: {
    siteTypeFilter(type) {
      return siteTypeMap[type]
    }
  },
  data() {
    return {
      buttonColor: buttonColor,
      indexs: 1,
      searchVisible: false,
      searchList: null,
      listLoadingSearch: true,
      totalSearch: 0,
      listQuerySearch: {
        page: 1,
        limit: 20,
        fequipmentno: undefined,
        sort: 'create_time',
        order: 'desc'
      },

      getListfclassstno: null,
      getListfequipmenttype: null,
      getListfchecktypeno: null,

      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        fequipmentno: undefined,
        fequipmentname: undefined,
        fclassstno: undefined,
        funit: undefined,
        fbrand: undefined,
        fspec: undefined,
        fuseyear: undefined,
        fimage: undefined,
        fequipmenttype: undefined,
        fpanel: undefined,
        fbarcode: undefined,
        fbuyprice: undefined,
        fupddate: undefined,
        foperator: undefined,
        sort: 'create_time',
        order: 'desc'
      },
      siteTypeList: [
        { value: 1, label: '是' },
        { value: 0, label: '否' }
      ],
      dataForm: {
        fequipmentno: undefined,
        fequipmentname: undefined,
        fclassstno: undefined,
        funit: undefined,
        fbrand: undefined,
        fspec: undefined,
        fuseyear: undefined,
        fimage: undefined,
        fequipmenttype: undefined,
        fpanel: undefined,
        fbarcode: undefined,
        fbuyprice: undefined,
        fupddate: undefined,
        foperator: undefined,
        id: undefined,
        details2: []
      },
      actionsTmp: [],
      listTmp: [],
      dialogFormVisible1: false,
      dialogStatus1: '',
      dataForm1: {
        fline: undefined
      },

      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建',
      },
      tableColor: tableColor,
      titleColor: titleColor,
      rules: {
        fequipmentno: [{ required: true, message: '设备编号不能为空' }],
        fequipmentname: [{ required: true, message: '设备名称不能为空' }],
        fclassstno: [{ required: true, message: '设备分类不能为空' }],
        funit: [],
        fbrand: [],
        fspec: [],
        fuseyear: [{ type: 'number', message: '使用年限必须为数字值', transform: (value) => Number(value) }],
        fimage: [],
        fequipmenttype: [
          { required: true, message: '设备类型不能为空' },
          { type: 'number', message: '设备类型必须为数字值', transform: (value) => Number(value) }
        ],
        fpanel: [
          { required: true, message: '是否有控制面板不能为空' },
          { type: 'number', message: '是否有控制面板必须为数字值', transform: (value) => Number(value) }
        ],
        fbarcode: [],
        fbuyprice: [],
        fupddate: [],
        foperator: []
      },
      rules1: {
        fline: [
          { required: true, message: '行号不能为空' },
          { type: 'number', message: '行号必须为数字值', transform: (value) => Number(value) }
        ],
        fcheckitemno: [{ required: true, message: '巡查项目编号不能为空' }],
        fcheckitemname: [],
        fchecktypeno: [
          { required: true, message: '巡查类型不能为空' },
          { type: 'number', message: '巡查类型必须为数字值', transform: (value) => Number(value) }
        ],
        fcheckflag: [{ type: 'number', message: '是否启用必须为数字值', transform: (value) => Number(value) }],
        fmemo: [],
        fupddate: [],
        foperator: []
      }
    }
  },
  created() {
    this.getList()
    this.getSearchList()
    getListArea({ flag: 2 })
      .then(response => {
        this.getListfclassstno = response.data.data.list
      })
      .catch(() => {
        this.getListfclassstno = []
      })
    getListArea({ flag: 1 })
      .then(response => {
        this.getListfequipmenttype = response.data.data.list
      })
      .catch(() => {
        this.getListfequipmenttype = []
      })
    getListArea({ flag: 15 })
      .then(response => {
        this.getListfchecktypeno = response.data.data.list
      })
      .catch(() => {
        this.getListfchecktypeno = []
      })
  },
  methods: {
    datetimeFormat(row, column) {
      const date = row[column.property]
      if (date === undefined || date === null) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD HH:mm:ss')
    },
    formatfclassstno: function(row, column) {
      if (this.getListfclassstno.length > 0) {
        for (let i = 0; i < this.getListfclassstno.length; i++) {
          if (row.fclassstno === this.getListfclassstno[i].value) {
            return this.getListfclassstno[i].label
          }
        }
        return ''
      } else {
        return ''
      }
    },
    formatfequipmenttype: function(row, column) {
      if (this.getListfequipmenttype.length > 0) {
        for (let i = 0; i < this.getListfequipmenttype.length; i++) {
          if (row.fequipmenttype === this.getListfequipmenttype[i].value) {
            return this.getListfequipmenttype[i].label
          }
        }
        return ''
      } else {
        return ''
      }
    },
    formatfchecktypeno: function(row, column) {
      if (this.getListfchecktypeno.length > 0) {
        for (let i = 0; i < this.getListfchecktypeno.length; i++) {
          if (row.fchecktypeno == this.getListfchecktypeno[i].value) {
            return this.getListfchecktypeno[i].label
          }
        }
        return ''
      } else {
        return ''
      }
    },
    // 获取搜索列表
    getSearchList() {
      this.listLoadingSearch = true
      listinfo(this.listQuerySearch)
        .then(response => {
          this.searchList = response.data.data.list
          this.totalSearch = response.data.data.total
          this.listLoadingSearch = false
        })
        .catch(() => {
          this.searchList = []
          this.totalSearch = 0
          this.listLoadingSearch = false
        })
    },

    searchFilter() {
      this.listQuerySearch.page = 1
      this.getSearchList()
    },

    searchData(row) {
      this.searchVisible = false
      this.dataForm.fequipmentno = row.feuipmentid
      this.dataForm.fequipmentname = row.fequipmentname
      this.dataForm.fclassstno = row.fclassstno
      this.dataForm.fbrand = row.fbrand
      this.dataForm.funit = row.funit
      this.dataForm.fuseyear = row.fuseyear
      this.dataForm.fspec = row.fspec
      this.dataForm.fequipmenttype = row.fequipmenttype
      this.dataForm.fpanel = row.fpanel
      this.dataForm.fbarcode = row.fbarcode
      this.dataForm.fbuyprice = row.fbuyprice
    },

    // 搜索弹出框
    searchDialog() {
      this.searchVisible = true
    },
    getList() {
      this.listLoading = true
      listinfo(this.listQuery)
        .then((response) => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        fequipmentno: undefined,
        fequipmentname: undefined,
        fclassstno: undefined,
        funit: undefined,
        fbrand: undefined,
        fspec: undefined,
        fuseyear: undefined,
        fimage: undefined,
        fequipmenttype: undefined,
        fpanel: undefined,
        fbarcode: undefined,
        fbuyprice: undefined,
        fupddate: undefined,
        foperator: undefined,
        id: undefined,
        details2: []
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dataForm.foperator = this.$store.state.user.id
          this.dataForm.fupddate = new Date()
          createinfo(this.dataForm)
            .then((response) => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '添加设备资料成功'
              })
              this.indexs = 1
            })
            .catch((response) => {
              this.$notify.error({
                title: '失败',
                message: response.data.data
              })
            })
        }
      })
    },
    handleUpdate(row) {
      this.listTmp = row
      this.actionsTmp = []
      row.details2.forEach((v) => {
        this.actionsTmp.push(v)
      })

      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      var end = row.details2[row.details2.length - 1]
      console.log(row)
      this.indexs = end.fline + 1
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dataForm.foperator = this.$store.state.user.id
          this.dataForm.fupddate = new Date()
          updateinfo(this.dataForm, this.$route.query.id)
            .then(() => {
              for (const v of this.list) {
                if (v.feuipmentid === this.dataForm.feuipmentid) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新设备资料成功'
              })
            })
            .catch((response) => {
              this.$notify.error({
                title: '失败',
                message: response.data.data
              })
            })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('是否要删除设备资料', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteinfo(row)
          .then((response) => {
            this.$notify.success({
              title: '成功',
              message: '删除设备资料成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch((response) => {
            this.$notify.error({
              title: '失败',
              message: response.data.data
            })
          })
      })
    },
    indexMethod(index) {
      index = index + 1
      return index
    },

    handleUpdate1() {
      this.dataForm1 = {
        fline: this.indexs
      }
      this.dataForm1.fcheckflag = 1
      this.dialogStatus1 = 'create'
      this.dialogFormVisible1 = true
      this.$nextTick(() => {
        this.$refs['dataForm1'].clearValidate()
      })
    },

    handleDelete1(row) {
      const index = this.dataForm.details2.indexOf(row)
      this.dataForm.details2.splice(index, 1)
      // this.dataForm.details2.pop(row)
    },
    addData() {
      this.$refs['dataForm1'].validate((valid) => {
        this.dataForm1.fline = this.indexs
        if (valid) {
          this.dialogFormVisible1 = false
          this.dataForm.details2.push(this.dataForm1)
          this.indexs++
        }
      })
    },
    // 弹窗点击关闭前的回调
    handleClose() {
      this.indexs = 1
      this.dialogFormVisible = false
      this.list.forEach((v) => {
        if (v.feuipmentid === this.dataForm.feuipmentid) {
          this.dataForm = this.listTmp
          this.dataForm.details2 = this.actionsTmp
          const index = this.list.indexOf(v)
          this.list.splice(index, 1, this.dataForm)
          return
        }
      })
    },
    cancel() {
      this.indexs = 1
      this.dialogFormVisible = false
      this.list.forEach((v) => {
        if (v.feuipmentid === this.dataForm.feuipmentid) {
          this.dataForm = this.listTmp
          this.dataForm.details2 = this.actionsTmp
          const index = this.list.indexOf(v)
          this.list.splice(index, 1, this.dataForm)
          return
        }
      })
    }
  }
}
</script>
